package com.gxwz.document.business.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;

import org.apache.struts2.ServletActionContext;
import org.aspectj.weaver.patterns.TypePatternQuestions.Question;

import com.gxwz.document.core.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("serial")
public class DownloadAction extends BaseAction {
	protected static final String LIST_JSP = "/WEB-INF/page/literatureManage/Literature_list.jsp";
	
	//下载文件的名字
	private String fileName;
	
	//文件存放的根包，自动注册过来
	private String savePath;
	
	private InputStream targetFile;

	//清理第一次信息，每次就都会有第一次，不会产生第二次，非常重要啵，ok啦--当第一次失败之后，以后所有的连接就都会返回input的页面
    @Override  
    public void validate() {  
        super.validate();  
        clearFieldErrors();  
    }
    /*
	 * 下载用的Action应该返回一个InputStream实例
	 * 该方法对应在一个配置的result里面的inputName属性值为targetFile
	 */
    public InputStream getTargetFile()throws Exception{
    	targetFile = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
    	
    	if (targetFile == null) {   
            // Find the inputstream from the invocation variable stack  
    		System.err.println("targetFile:"+targetFile);
    		System.err.println("fileName:"+fileName);
    		System.err.println(ServletActionContext.getServletContext().getRealPath("/upload"));
    		String targetFile1 = ServletActionContext.getServletContext().getRealPath("/upload")+ "/"+fileName;
    		System.err.println("targetFile1:"+targetFile1);
    		InputStream targetFile2 = ServletActionContext.getServletContext().getResourceAsStream(targetFile1);
    		System.err.println("targetFile2:"+targetFile2);
    	}
    	
        return targetFile;
    }
    
    /**
     * 1.显示所有要下载文件的列表
     */
    public String download() throws Exception{
        //得到upload目录路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        //目录对象
        File file = new File(path);
        //得到所有要下载的文件的文件名
        String[] fileNames = file.list();
        //保存
        ActionContext ac = ActionContext.getContext();
        //得到代表request的map
        //这种形式也是Ok的ac.getContextMap();
        Map<String,Object> request = (Map<String, Object>) ac.get("request");
        request.put("fileNames", fileNames);
        setForwardView(LIST_JSP);
		return SUCCESS;
    }
    
    
    public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		try {
			this.savePath = new String(savePath.getBytes(),"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
		this.savePath = savePath;
	}

	public String getFileName() {
		try {
            fileName = new String(fileName.getBytes(),"ISO-8859-1");
            System.err.println("get--fileName:"+fileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
		return fileName;
	}
	
	  /**
     * 2.文件下载
     */
    //2.1.获取要下载的文件的文件名
    public void setFileName(String fileName) throws UnsupportedEncodingException{
        //鼠标移至下载处，显示的文件名使用的是get方式提交，所以要解决中文乱码问题
      try {
           /* fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");*/
    	  this.fileName = new String(fileName.getBytes(),"ISO-8859-1");
            System.err.println("set--fileName:"+fileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //处理好的文件名，赋值
        this.fileName = fileName;
    }
    
  //2.4.下载显示的文件名（浏览器显示的文件名）
    public String getDownFileName()throws UnsupportedEncodingException{
        //需要进行中文编码
        try {
            fileName = URLEncoder.encode(fileName,"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }
}
